﻿(function () {
    appModule.controller('common.views.users.createOrEditModal', [
        '$scope', '$uibModalInstance', 'abp.services.app.user', 'userId', 'abp.services.app.area', 'user',
        function ($scope, $uibModalInstance, userService, userId, areaService, user) {
            var vm = this;
            vm.saving = false;
            vm.user = null;
            vm.profilePictureId = null;
            vm.roles = [];
            //vm.setRandomPassword = (userId == null);
            vm.setRandomPassword = false;
            //vm.sendActivationEmail = (userId == null);
            vm.sendActivationEmail = false;
            vm.canChangeUserName = true;
            vm.isTwoFactorEnabled = abp.setting.getBoolean("Abp.Zero.UserManagement.TwoFactorLogin.IsEnabled");
            vm.isLockoutEnabled = abp.setting.getBoolean("Abp.Zero.UserManagement.UserLockOut.IsEnabled");

            vm.save = function () {
                var assignedRoleNames = _.map(
                    _.where(vm.roles, { isAssigned: true }), //Filter assigned roles
                    function (role) {
                        return role.roleName; //Get names
                    });

                if (vm.setRandomPassword) {
                    vm.user.password = null;
                }

                vm.saving = true;

                vm.user.emailAddress = vm.guid() + "@126.com";
                vm.user.surname = "默认姓氏";
                if (vm.user.townID == null) {
                    vm.user.townID = 0;
                }
                if (vm.user.areaID == null) {
                    vm.user.areaID = 0;
                }
                if (vm.user.villageID == null) {
                    vm.user.villageID = 0;
                }

                userService.createOrUpdateUser({
                    user: vm.user,
                    assignedRoleNames: assignedRoleNames,
                    sendActivationEmail: vm.sendActivationEmail,
                    setRandomPassword: vm.setRandomPassword
                }).then(function () {
                    abp.notify.info(app.localize('SavedSuccessfully'));
                    $uibModalInstance.close();
                }).finally(function () {
                    vm.saving = false;
                });
            };

            vm.guid = function () {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "";

                var uuid = s.join("");
                return uuid;
            }

            vm.cancel = function () {
                $uibModalInstance.dismiss();
            };

            vm.getAssignedRoleCount = function () {
                return _.where(vm.roles, { isAssigned: true }).length;
            };

            function init() {
                //绑定网格员类型
                var userTypeData = { data: [{ 'name': '非群众', 'value': '非群众' }, { 'name': '群众', 'value': '群众' }] };
                vm.userTypeList = userTypeData.data;

                //绑定镇控件
                areaService.getAreaByLevelAsync({ id: 0 }).then(function (result) {
                    vm.townList = result.data.items;
                });

                if (userId != null) {
                    //绑定区控件
                    areaService.getAreaByLevelAsync({ id: user.townID }).then(function (result) {
                        vm.areaList = result.data.items;
                    });

                    //绑定村控件
                    areaService.getAreaByLevelAsync({ id: user.areaID }).then(function (result) {
                        vm.villageList = result.data.items;

                        userService.getUserForEdit({
                            id: userId
                        }).then(function (result) {
                            vm.user = result.data.user;
                            vm.profilePictureId = result.data.profilePictureId;
                            vm.user.passwordRepeat = vm.user.password;
                            vm.roles = result.data.roles;
                            vm.canChangeUserName = vm.user.userName != app.consts.userManagement.defaultAdminUserName;
                        });
                    });
                }
                else {
                    userService.getUserForEdit({
                        id: userId
                    }).then(function (result) {
                        vm.user = result.data.user;
                        vm.profilePictureId = result.data.profilePictureId;
                        vm.user.password = '111111';
                        vm.user.passwordRepeat = '111111';
                        vm.roles = result.data.roles;
                        vm.canChangeUserName = vm.user.userName != app.consts.userManagement.defaultAdminUserName;
                        vm.user.shouldChangePasswordOnNextLogin = false;
                        vm.user.userType = "非群众";
                    });
                }
            }

            //绑定区
            vm.bindArea = function (townID) {
                if (townID != null) {
                    areaService.getAreaByLevelAsync({ id: townID }).then(function (result) {
                        vm.areaList = result.data.items;
                    });
                }
            };

            //绑定村
            vm.bindVillage = function (areaID) {
                if (areaID != null) {
                    areaService.getAreaByLevelAsync({ id: areaID }).then(function (result) {
                        vm.villageList = result.data.items;
                    });
                }
            };

            init();
        }
    ]);
})();